<template>
  <div class="message-search-container">
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="关键词">
        <el-input 
          v-model="searchForm.keyword" 
          placeholder="输入消息内容关键词" 
          clearable 
          @keyup.enter="handleSearch"
        />
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="x"
          @change="handleTimeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
    
    <div v-if="loading" class="loading">
      <el-spin />
    </div>
    
    <el-table v-else :data="messages" class="message-table" border>
      <el-table-column label="类型" width="80">
        <template #default="{row}">
          <el-tag :type="row.receiver_type === 1 ? 'primary' : 'success'" size="small">
            {{ row.receiver_type === 1 ? '单聊' : '群聊' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sender_name" label="发送者" width="150">
        <template #default="{row}">
          <div class="sender-info">
            <el-avatar :src="row.sender_avatar" :size="30" />
            <span>{{ row.sender_name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="消息内容" />
      <el-table-column label="会话" width="180">
        <template #default="{row}">
          <div v-if="row.receiver_type === 1" class="chat-info">
            <span>私聊会话</span>
          </div>
          <div v-else class="chat-info">
            <el-avatar :src="row.group_avatar" :size="24" class="group-avatar" />
            <span>{{ row.group_name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="timestamp" label="时间" width="180">
        <template #default="{row}">
          {{ formatTime(row.timestamp) }}
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      v-if="total > 0"
      class="pagination"
      v-model:current-page="searchForm.page"
      :page-size="searchForm.page_size"
      layout="total, prev, pager, next"
      :total="total"
      @current-change="handlePageChange"
    />
    
    <div v-if="!loading && messages.length === 0" class="empty">
      <el-empty description="暂无搜索结果" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import chatApi from '@/api/chat'
import { formatDateTime } from '@/utils/timeUtils'
import { ElMessage } from 'element-plus'

// 响应式数据
const router = useRouter()
const route = useRoute()
const searchForm = ref({
  keyword: '',
  start_time: '',
  end_time: '',
  page: 1,
  page_size: 10
})
const timeRange = ref([])
const messages = ref([])
const total = ref(0)
const loading = ref(false)

// 初始化搜索参数
onMounted(() => {
  const { keyword, start, end } = route.query  // 对于链接中带有参数的访问进行初始化搜索的处理
  if (keyword) searchForm.value.keyword = keyword
  
  // 修复：从路由参数初始化时间范围并同步到timeRange
  if (start && end) {
    const startTime = Number(start)
    const endTime = Number(end)
    searchForm.value.start_time = startTime
    searchForm.value.end_time = endTime
    // 同步到date-picker的timeRange
    timeRange.value = [startTime, endTime]
  }
  
  // 有初始参数则自动搜索
  if (keyword || (start && end)) {
    handleSearch()
  }
})

// 处理时间范围变化
const handleTimeChange = (dates) => {
  if (dates && dates.length === 2 && dates[0] && dates[1]) {
    [searchForm.value.start_time, searchForm.value.end_time] = dates
  } else {
    searchForm.value.start_time = ''
    searchForm.value.end_time = ''
    // 确保timeRange也被清空
    timeRange.value = []
  }
}

// 执行搜索
const handleSearch = async () => {
  loading.value = true
  try {
    // 准备搜索参数，过滤掉空的时间参数
    const searchParams = {
      ...searchForm.value
    }
    
    // 只在有值时传递时间参数
    if (!searchParams.start_time) delete searchParams.start_time
    if (!searchParams.end_time) delete searchParams.end_time
    
    // 注意：request.js中的响应拦截器已经直接返回了data.data部分
    const data = await chatApi.searchMessages(searchParams)
    console.log('搜索结果数据:', data)
    
    // 直接使用返回的数据，不再需要response.code判断（错误已在拦截器中处理）
    messages.value = data.messages || []
    // 修复：从响应数据中获取total，API中返回的数据结构包含page和page_size但没有明确的total
    total.value = data.total || messages.value.length
    
    // 更新路由参数 - 修复：只在有值时传递时间参数
    const queryParams = {
      ...route.query,
      keyword: searchForm.value.keyword || undefined
    }
    
    // 只有当时间范围有值时才添加到路由参数
    if (searchForm.value.start_time && searchForm.value.end_time) {
      queryParams.start = searchForm.value.start_time
      queryParams.end = searchForm.value.end_time
    } else {
      // 移除空的时间参数
      delete queryParams.start
      delete queryParams.end
    }
    
    router.replace({ query: queryParams })
  } catch (error) {
    ElMessage.error('搜索失败: ' + (error.message || '网络异常'))
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  searchForm.value.page = page
  handleSearch()
}

// 格式化时间
const formatTime = (timestamp) => {
  return formatDateTime(timestamp)
}
</script>

<style scoped>
.message-search-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-form {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.sender-info {
  display: flex;
  align-items: center;
}

.avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 8px;
    object-fit: cover;
  }
  
  .chat-info {
    display: flex;
    align-items: center;
  }
  
  .group-avatar {
    margin-right: 6px;
  }

.message-table {
  margin: 20px 0;
}

.pagination {
  text-align: right;
  margin-top: 15px;
}

.loading {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.empty {
  text-align: center;
  padding: 40px 0;
}
</style>